import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { useGlobSetting } from '/@/hooks/setting';

const { createMessage, createWarningModal } = useMessage();
const glob = useGlobSetting();

/**
 * 导出文件xlsx的mime-type
 */
export const XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
/**
 * 导出文件xlsx的文件后缀
 */
export const XLSX_FILE_SUFFIX = '.xlsx';

export function useMethods() {
  /**
   * 导出xls
   * @param name
   * @param url
   */
  async function exportXls(name, url, params, isXlsx = false) {
    createMessage.loading({
      content: '正在导出, 请耐心等待...',
      key: 'export_loading'
    });
    defHttp.get({ url: url, params: params, responseType: 'blob' }, { isTransformResponse: false }).then(data => {
      createMessage.destroy('export_loading')
      if (!data) {
        createMessage.warning('文件下载失败');
        return;
      }
      if (!name || typeof name != 'string') {
        name = '导出文件';
      }
      let blobOptions = { type: 'application/vnd.ms-excel' };
      let fileSuffix = '.xls';
      if (isXlsx === true) {
        blobOptions['type'] = XLSX_MIME_TYPE;
        fileSuffix = XLSX_FILE_SUFFIX;
      }
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix);
      } else {
        let url = window.URL.createObjectURL(new Blob([data], blobOptions));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', name + fileSuffix);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); //下载完成移除元素
        window.URL.revokeObjectURL(url); //释放掉blob对象
      }
    }).catch((res) => {
      createMessage.destroy('export_loading')
      console.log(res)
    })
    
  }

  /**
   * 导入xls
   * @param data 导入的数据
   * @param url
   * @param success 成功后的回调
   */
  async function importXls(data, url, success, fail) {
    const isReturn = (fileInfo) => {
      createMessage.destroy('import_loading')
      try {
        if (fileInfo.code === 201) {
          let {
            message,
            result: { msg, fileUrl, fileName },
          } = fileInfo;
          let href = glob.uploadUrl + fileUrl;
          createWarningModal({
            title: message,
            centered: false,
            content: `<div>
                        <span>${msg}</span><br/> 
                        <span>具体详情请<a href = ${href} download = ${fileName}> 点击下载 </a> </span> 
                      </div>`,
          });
        } else if (fileInfo.code !== 1) {
          createWarningModal({
            width: 600,
            bodyStyle: {
              maxHeight: 'calc(100vh - 200px)',
              overflowY: 'auto'
            },
            title: `${data.file.name} 导入失败`,
            centered: false,
            content: fileInfo.message
          })
        } else {
          createMessage.success(fileInfo.message || `${data.file.name} 文件上传成功`);
        }
      } catch (error) {
        console.log('导入的数据异常', error);
        fail && fail(error)
      } finally {
        typeof success === 'function' ? success(fileInfo) : '';
      }
    };

    createMessage.loading({
      content: '正在导入, 请耐心等待...',
      key: 'import_loading'
    });
    defHttp.uploadFile({ url }, { file: data.file }, { success: isReturn })
      .catch(e =>  fail && fail(e))
      .finally(() => createMessage.destroy('import_loading')) 
  }

  return {
    handleExportXls: (name: string, url: string, params?: object) => exportXls(name, url, params),
    handleImportXls: (data, url, success, fail) => importXls(data, url, success, fail),
    handleExportXlsx: (name: string, url: string, params?: object) => exportXls(name, url, params, true),
  };
}
